package com.hschinese.pronunciation.widget;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.AppDataBean;
import com.hschinese.pronunciation.bean.AppResourceMap;
import com.hschinese.pronunciation.bean.LearnRecordBean;
import com.hschinese.pronunciation.db.DBHelper;
import com.hschinese.pronunciation.interfaces.LessonProgressInterface;
import com.hschinese.pronunciation.interfaces.NextLessonInterface;
import com.hschinese.pronunciation.interfaces.PlayClickListener;
import com.hschinese.pronunciation.interfaces.RecordStatusListener;
import com.hschinese.pronunciation.interfaces.VolumeListener;
import com.hschinese.pronunciation.utils.AnimatorUtil;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.SimpleRecordUtil;
import com.hschinese.pronunciation.utils.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.hschinese.pronunciation.R.id.study_tone_img_1;

/**
 * Created by wo on 2015/11/5.
 */
public class StudyWordsView extends LinearLayout{
    private Activity mContext = null;
    private View mView = null;
    private ImageView mToneImage = null;
    private ImageView study_tone_img2 = null;
    private ImageView mToneImageBg = null;
    private ImageView mDoubleToneImage;
    private ImageView study_tone_img_2;
    private ImageView mDoubleToneImageBg;
    private ImageView iv_mulu_circel;
    private PlayControlView mPlayController = null;
    private TextView mToneTextView = null;
    private LinearLayout ll_mulu_circel = null;
    private Cursor cursor;

    private int lessonType = 0;
    private int currentPosition = 0;
    private List<AppDataBean> mDataList;


    private LessonProgressInterface mListener = null;
    private NextLessonInterface mNextListener = null;
    private String mMp3SourceDir = null;
    private boolean isFirst = true;
    private int bg1Id, bg2id;


    public StudyWordsView(Context context) {
        super(context);
       initViews(context);
    }

    public StudyWordsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews(context);
    }
    private void initViews(Context context) {
        mContext = (Activity)context;
        mView = LayoutInflater.from(context).inflate(R.layout.study_layout_t, null);
        mPlayController = (PlayControlView)mView.findViewById(R.id.study_play_controller);
        ll_mulu_circel = (LinearLayout) mView.findViewById(R.id.ll_mulu_circel);
        iv_mulu_circel = (ImageView) mView.findViewById(R.id.iv_mulu_circel);
        mPlayController.isUseScore(false);
        mToneImage = (ImageView)mView.findViewById(R.id.study_tone_img);
        study_tone_img2 = (ImageView)mView.findViewById(R.id.study_tone_img2);
        mToneImageBg = (ImageView)mView.findViewById(R.id.study_tone_img_bg);
        mDoubleToneImage = (ImageView)mView.findViewById(study_tone_img_1);
        study_tone_img_2 = (ImageView)mView.findViewById(R.id.study_tone_img_2);
        mDoubleToneImageBg = (ImageView)mView.findViewById(R.id.study_tone_img_1_bg);
        mToneTextView = (TextView)mView.findViewById(R.id.study_syllable);
        Typeface type = Typeface.createFromAsset(getContext().getAssets(), "fonts/hanyupinyin.ttf");
        mToneTextView.setTypeface(type);
        mPlayController.setPlayClickListener(new PlayClickListener() {
            @Override
            public void onPlayClicked(boolean isPlaying) {
                setAnimation();
            }
        });
        this.addView(mView);
    }

    private void setFirstAnimation() {
        if (lessonType == 0) {
            mToneImageBg.setImageResource(R.drawable.single_tone_anim);
            final AnimationDrawable animationDrawable1 = (AnimationDrawable) mToneImageBg.getDrawable();
            animationDrawable1.setOneShot(true);
            ViewTreeObserver.OnPreDrawListener preDrawListener = new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    animationDrawable1.start();
                    return true;
                }
            };
            mToneImageBg.getViewTreeObserver().addOnPreDrawListener(preDrawListener);
        } else {
            mDoubleToneImageBg.setImageResource(R.drawable.double_tone_anim);
            final AnimationDrawable animationDrawable = (AnimationDrawable) mDoubleToneImageBg.getDrawable();
            animationDrawable.setOneShot(true);
            ViewTreeObserver.OnPreDrawListener preDrawListener = new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    animationDrawable.start();
                    return true;
                }
            };
            mDoubleToneImageBg.getViewTreeObserver().addOnPreDrawListener(preDrawListener);
        }
    }

    public void initData() {
        mDataList = new ArrayList<AppDataBean>();
        cursor = DBHelper.getInstance(mContext).query(DBHelper.RES_TABLE, " type=? ", new String[]{lessonType + ""});
        if (cursor != null)
            Logger.e("xionghy-cursor: " + cursor.getCount());
        while(cursor.moveToNext()) {
            AppDataBean d = new AppDataBean();
            d.setChinese(cursor.getString(cursor.getColumnIndex("chinese")));
            d.setPinyin(cursor.getString(cursor.getColumnIndex("pinyin")));
            d.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            d.setTone(cursor.getString(cursor.getColumnIndex("tone")));
            d.setAudioName(cursor.getString(cursor.getColumnIndex("audioName")));
            d.setPicName(cursor.getString(cursor.getColumnIndex("picName")));
            d.setType(cursor.getInt(cursor.getColumnIndex("type")));
            d.setGroupID(cursor.getInt(cursor.getColumnIndex("groupId")));
            d.setWeight(cursor.getInt(cursor.getColumnIndex("weight")));
            mDataList.add(d);
        }
        if (mDataList.size() <= 0) {
            Logger.e("获取到的数据为空。。。。");
            return;
        }
        ll_mulu_circel.removeAllViews();

        updateViewData();
    }

    public void setLessonType(int type) {
        lessonType = type;
        if (lessonType == 0) {
            mToneImage.setVisibility(View.VISIBLE);
            study_tone_img2.setVisibility(View.VISIBLE);
            mDoubleToneImage.setVisibility(View.GONE);
            study_tone_img_2.setVisibility(View.GONE);
            mDoubleToneImageBg.setVisibility(View.GONE);
        } else if (lessonType == 2) {
            mToneImage.setVisibility(View.GONE);
            mToneImageBg.setVisibility(View.GONE);
            study_tone_img2.setVisibility(View.GONE);
            study_tone_img_2.setVisibility(View.VISIBLE);
            mDoubleToneImage.setVisibility(View.VISIBLE);
            mDoubleToneImageBg.setVisibility(View.VISIBLE);
        }
    }


    public void nextWord() {
        // TODO 数据切换，涉及到界面上文字和图片的切换
        mPlayController.resetProgressBar();
        currentPosition ++;
        if (currentPosition < mDataList.size()) {
            updateViewData();
            AnimatorUtil.slideIn(this, 500, 0, new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mPlayController.playStandard();
                    setAnimation();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        } else {
            Utils.showDialog(mContext, R.string.next_lesson_dialog_msg, lessonType, mNextListener);
        }
    }

    private void setAnimation() {
        AnimationDrawable drawable;
        if (lessonType == 0) {
            mToneImageBg.setImageResource(bg1Id);
            mToneImageBg.setImageResource(R.drawable.single_tone_anim);
            drawable = (AnimationDrawable) mToneImageBg.getDrawable();
        } else {
            mDoubleToneImageBg.setImageResource(bg2id);
            mDoubleToneImageBg.setImageResource(R.drawable.double_tone_anim);
            drawable = (AnimationDrawable) mDoubleToneImageBg.getDrawable();
        }
        drawable.setOneShot(true);
        drawable.start();
    }

    private void startTask(float t, final AnimationDrawable draw) {
        if (draw == null) return;
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                draw.stop();
            }
        }, (int) (t * 1000));
    }

    public void beforeWord() {
        if (currentPosition <= 0)
            return;
        mPlayController.resetProgressBar();
        currentPosition --;
        if (currentPosition < mDataList.size()) {
            updateViewData();
            AnimatorUtil.slideOut(this, 500, 0, new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }
                @Override
                public void onAnimationEnd(Animation animation) {
                    mPlayController.playStandard();
                    setAnimation();
                }
                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        } else {
            // TODO 进入下一课. 会掉到StudyActivity页面来进行View的切换
            mNextListener.onLessonChanged(lessonType - 1);
        }
    }

    public void setListener(LessonProgressInterface listener) {  mListener = listener; }

    public void setNextListener(NextLessonInterface listener) { mNextListener = listener; }

    public void setVolumeListener(VolumeListener l) { mPlayController.setVolumeListener(l); }

    public void setRecordListener(RecordStatusListener l) { mPlayController.setRecordListener(l); }

    /**
     *  TODO 拿到对应的数据来进行设置，显示字符，进度条，换取对应的播放地址
     */
    private void updateViewData() {
        if (currentPosition < 0) return;
        mToneTextView.setText(mDataList.get(currentPosition).getPinyin().replace("|", " "));
        if (mListener != null) {
            mListener.setProgress(mDataList.size(), currentPosition);
        }
        AppDataBean data = mDataList.get(currentPosition);
        mMp3SourceDir = AppResourceMap.getMp3Fold(lessonType) + data.getAudioName().replace("|", "") + ".mp3";
        Logger.e("xionghy - audio dir: " + mMp3SourceDir);
        mPlayController.setStandardUrl(mMp3SourceDir);
        mPlayController.setPlayRecordVisibility(View.INVISIBLE);
        if (lessonType == 0) {
            bg1Id = Utils.getResId(mContext, "ic_tone_w" + data.getTone().replace("|", ""), "drawable");
            mToneImage.setImageResource(Utils.getResId(mContext, "ic_tone_w" + data.getTone().replace("|", ""), "drawable"));
            mToneImageBg.setImageResource(Utils.getResId(mContext, "ic_tone_w" + data.getTone().replace("|", ""), "drawable"));
        } else if (lessonType == 2) {
            bg2id = Utils.getResId(mContext, "ic_tone_w" + data.getTone().replace("|", ""), "drawable");
            mDoubleToneImage.setImageResource(Utils.getResId(mContext, "ic_tone_w" + data.getTone().replace("|", ""), "drawable"));
            mDoubleToneImageBg.setImageResource(Utils.getResId(mContext, "ic_tone_w" + data.getTone().replace("|", ""), "drawable"));
        }
        if (currentPosition == 0) {
            mPlayController.playStandard();
            setFirstAnimation();
        }
        addLearnRecord(data);
    }

    private void addLearnRecord(AppDataBean data) {
        LearnRecordBean bean = new LearnRecordBean();
        bean.setChinese(data.getChinese());
        bean.setLearnedTimes(1);
        bean.setLearnType(lessonType + "");
        bean.setRecordID(data.getType() + "|" + data.getWeight());
        bean.setTimestamp(System.currentTimeMillis() + "");
        DBHelper.getInstance(mContext).insertLearnRecord(bean);
    }

    public void onDestroy() {
        SimpleRecordUtil.getInstance(mContext).stopPlayer();
        SimpleRecordUtil.getInstance(mContext).stopRecorder();
        if (mPlayController != null) {
            mPlayController.destory();
        }
        if (cursor != null)
            cursor.close();
    }
}
